﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Gamemaster.Naming
{
    public static class Names
    {
        private static readonly object syncRoot = new object();
        private static INameDatabaseFactory _databaseFactory;

        public static INameDatabaseFactory DatabaseFactory 
        {
            get
            {
                lock (syncRoot)
                {
                    if (_databaseFactory == null)
                    {
                        if (LinqDatabaseFactory.ConfigurationExists())
                        {
                            Names.DatabaseFactory = new LinqDatabaseFactory();
                        }
                        else
                        {
                            Names.DatabaseFactory = new DummyDatabaseFactory();
                        }
                    }
                }

                return _databaseFactory;
            }
            set
            {
                lock (syncRoot)
                {
                    _databaseFactory = value;
                }
            }
        }

        public static IEnumerable<Name> Generate(int quantity, GenderOptions options)
        {
            List<Name> names = new List<Name>();

            INameDatabase context = DatabaseFactory.CreateDatabase();
            List<First> data = context.GetFirstNames(options);

            for (int i = 0; i < quantity && data.Count > 0; i++)
            {
                int index = Roll.d(data.Count) - 1;
                First record = data[index];
                data.RemoveAt(index);

                Name name = new Name();
                name.FirstName = record.Name;
                name.Gender = (GenderOptions)Enum.Parse(typeof(GenderOptions), record.Gender);

                names.Add(name);
            }

            return names;
        }
        public static Name GenerateOne(GenderOptions gender)
        {
            return Generate(1, gender).First();
        }
    }
}
